﻿using Future.Common.Exception;
using Future.IService;
using Microsoft.Extensions.Configuration;

namespace Future.Service
{
    /// <summary>
    /// 描述：文件处理服务
    /// 创建人： yangkai
    /// 创建时间：2022/12/22 11:23:35
    /// </summary>
    public class FileService : IFileService
    {
        private readonly IConfiguration _configuration;

        public FileService(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        public FileStream GetFile(string relativePath)
        {
            string rootPath = _configuration["RootPath"];
            string fullPath = Path.GetFullPath(Path.Combine(rootPath, relativePath));
            FileStream stream = File.OpenRead(fullPath);
            return stream;
        }

        public void WriteFile(string relativePath, MemoryStream memoryStream)
        {
            string rootPath = _configuration["RootPath"];
            string fullPath = Path.GetFullPath(Path.Combine(rootPath, relativePath));
            string directory = Path.GetDirectoryName(fullPath) ?? string.Empty;
            if (string.IsNullOrEmpty(directory))
            {
                throw new BusinessException("文件路径异常");
            }

            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }

            using var stream = new FileStream(fullPath, FileMode.CreateNew, FileAccess.Write);
            byte[] buffer = new byte[1024];
            int len;
            memoryStream.Position = 0;
            while ((len = memoryStream.Read(buffer, 0, buffer.Length)) > 0)
            {
                stream.Write(buffer, 0, len);
            }

            stream.Flush();
        }
    }
}
